package com.party.mobile.redisPubSub.listener;

import com.alibaba.druid.support.json.JSONUtils;
import com.party.mobile.biz.webSocket.WebSocketBizService;
import com.party.mobile.redisPubSub.subscribe.SubScribeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPubSub;

import java.util.Map;

/**
 * @Description: RedisMsgPubSubListener
 * @Author: yangshoukun
 * @Date: 2018/4/2 19:29
 */
@Component
public class RedisMsgPubSubListener extends JedisPubSub {

    private static Logger logger = LoggerFactory.getLogger(RedisMsgPubSubListener.class);

    @Autowired
    private WebSocketBizService webSocketBizService;

    // 向频道channel发消息时
    @Override
    public void onMessage(String channel, String message) {
        if (null == channel || null == message) {
            logger.info("redis发布消息时频道和消息不能为空");
            return;
        }
        if (SubScribeMessage.TRANSFER_CHANNEL_NAME.equals(channel)) {
            try {
                Map<String, String> jsonString = (Map<String, String>) JSONUtils.parse(message);
                String memberId = jsonString.get("memberId");
                String msg = jsonString.get("message");
                webSocketBizService.send(message, memberId);
            } catch (Exception e) {
                logger.error("众筹转移接受到发布的消息时出错, channel = {}, message = {}, 错误信息为 {}", channel, message, e);
            }
        }
    }

    @Override
    public void onPMessage(String pattern, String channel, String message) {
        System.out.println("------------");
    }
}
